<template>
  <div class="channel-monitor">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>渠道状态监控</span>
          <div class="header-actions">
            <el-button type="primary" @click="refreshStatus" :loading="refreshLoading">
              <el-icon><Refresh /></el-icon>
              刷新状态
            </el-button>
            <el-button @click="handleBatchTest" :loading="batchTestLoading">
              <el-icon><Connection /></el-icon>
              批量测试
            </el-button>
          </div>
        </div>
      </template>

      <!-- 状态统计 -->
      <el-row :gutter="20" class="status-statistics">
        <el-col :xs="24" :sm="12" :md="6">
          <div class="status-card connected" @click="filterByStatus('connected')">
            <div class="status-icon">
              <el-icon size="32" color="#67C23A">
                <CircleCheck />
              </el-icon>
            </div>
            <div class="status-info">
              <div class="status-count">{{ statusCounts.connected }}</div>
              <div class="status-label">正常连接</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <div class="status-card disconnected" @click="filterByStatus('disconnected')">
            <div class="status-icon">
              <el-icon size="32" color="#F56C6C">
                <CircleClose />
              </el-icon>
            </div>
            <div class="status-info">
              <div class="status-count">{{ statusCounts.disconnected }}</div>
              <div class="status-label">连接断开</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <div class="status-card warning" @click="filterByStatus('warning')">
            <div class="status-icon">
              <el-icon size="32" color="#E6A23C">
                <Warning />
              </el-icon>
            </div>
            <div class="status-info">
              <div class="status-count">{{ statusCounts.warning }}</div>
              <div class="status-label">状态警告</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <div class="status-card error" @click="filterByStatus('error')">
            <div class="status-icon">
              <el-icon size="32" color="#909399">
                <InfoFilled />
              </el-icon>
            </div>
            <div class="status-info">
              <div class="status-count">{{ statusCounts.error }}</div>
              <div class="status-label">状态异常</div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 搜索和筛选 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="渠道名称">
              <el-input v-model="searchForm.channelName" placeholder="请输入渠道名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="渠道类型">
              <el-select v-model="searchForm.channelType" placeholder="请选择渠道类型" clearable style="width: 100%">
                <el-option label="上游渠道" value="upstream" />
                <el-option label="下游渠道" value="downstream" />
                <el-option label="银行" value="bank" />
                <el-option label="消费金融" value="consumer_finance" />
                <el-option label="小贷公司" value="small_loan" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item label="连接状态">
              <el-select v-model="searchForm.connectionStatus" placeholder="请选择连接状态" clearable style="width: 100%">
                <el-option label="全部" value="" />
                <el-option label="正常" value="connected" />
                <el-option label="断开" value="disconnected" />
                <el-option label="警告" value="warning" />
                <el-option label="异常" value="error" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6">
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 渠道状态列表 -->
      <div class="channel-status-list">
        <el-row :gutter="20">
          <el-col 
            v-for="channel in filteredChannels" 
            :key="channel.id" 
            :xs="24" 
            :sm="12" 
            :md="8" 
            :lg="6"
          >
            <el-card 
              class="channel-card" 
              :class="getChannelStatusClass(channel)"
              shadow="hover"
            >
              <div class="channel-header">
                <div class="channel-name">{{ channel.channelName }}</div>
                <el-tag :type="getChannelTypeTag(channel.channelType)" size="small">
                  {{ getChannelTypeLabel(channel.channelType) }}
                </el-tag>
              </div>
              
              <div class="channel-status">
                <div class="status-indicator" :class="channel.connectionStatus">
                  <span class="status-dot"></span>
                  <span class="status-text">{{ getConnectionStatusText(channel.connectionStatus) }}</span>
                </div>
                <div class="last-check-time">最后检查: {{ formatTime(channel.lastCheckTime) }}</div>
              </div>

              <div class="channel-metrics">
                <div class="metric-item">
                  <span class="metric-label">成功率:</span>
                  <span class="metric-value" :class="getSuccessRateClass(channel.successRate)">
                    {{ channel.successRate }}%
                  </span>
                </div>
                <div class="metric-item">
                  <span class="metric-label">响应时间:</span>
                  <span class="metric-value">{{ channel.avgResponseTime }}ms</span>
                </div>
                <div class="metric-item">
                  <span class="metric-label">今日推送:</span>
                  <span class="metric-value">{{ channel.todayPushCount }}</span>
                </div>
              </div>

              <div class="channel-actions">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="handleTestConnection(channel)"
                  :loading="testLoadingMap[channel.id]"
                >
                  <el-icon><Connection /></el-icon>
                  测试连接
                </el-button>
                <el-button 
                  size="small" 
                  @click="handleViewDetails(channel)"
                >
                  <el-icon><View /></el-icon>
                  详情
                </el-button>
                <el-button 
                  size="small" 
                  @click="handleViewLogs(channel)"
                >
                  <el-icon><Document /></el-icon>
                  日志
                </el-button>
              </div>

              <!-- 状态异常时的详细信息 -->
              <div v-if="channel.connectionStatus !== 'connected' && channel.errorMessage" class="error-info">
                <el-alert
                  :title="channel.errorMessage"
                  type="error"
                  :closable="false"
                  size="small"
                />
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 空状态 -->
      <el-empty v-if="filteredChannels.length === 0 && !loading" description="暂无渠道数据" />
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialog.visible"
      title="渠道详情"
      width="700px"
      class="responsive-dialog"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="渠道名称">{{ detailDialog.data.channelName }}</el-descriptions-item>
        <el-descriptions-item label="渠道类型">
          <el-tag :type="getChannelTypeTag(detailDialog.data.channelType)">
            {{ getChannelTypeLabel(detailDialog.data.channelType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="连接状态">
          <el-tag :type="getConnectionStatusTag(detailDialog.data.connectionStatus)">
            {{ getConnectionStatusText(detailDialog.data.connectionStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="成功率">
          <span :class="getSuccessRateClass(detailDialog.data.successRate)">
            {{ detailDialog.data.successRate }}%
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="平均响应时间">{{ detailDialog.data.avgResponseTime }}ms</el-descriptions-item>
        <el-descriptions-item label="今日推送量">{{ detailDialog.data.todayPushCount }}</el-descriptions-item>
        <el-descriptions-item label="今日成功量">{{ detailDialog.data.todaySuccessCount }}</el-descriptions-item>
        <el-descriptions-item label="最后检查时间">{{ formatTime(detailDialog.data.lastCheckTime) }}</el-descriptions-item>
        <el-descriptions-item label="API地址" :span="2">{{ detailDialog.data.apiEndpoint }}</el-descriptions-item>
        <el-descriptions-item label="错误信息" :span="2" v-if="detailDialog.data.errorMessage">
          <el-alert
            :title="detailDialog.data.errorMessage"
            type="error"
            :closable="false"
            size="small"
          />
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 日志对话框 -->
    <el-dialog
      v-model="logsDialog.visible"
      title="连接日志"
      width="800px"
      class="responsive-dialog"
    >
      <el-table :data="logsDialog.logs" border style="width: 100%" max-height="400">
        <el-table-column prop="timestamp" label="时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.timestamp) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getConnectionStatusTag(row.status)">
              {{ getConnectionStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="responseTime" label="响应时间(ms)" width="120" />
        <el-table-column prop="message" label="信息" min-width="200" />
      </el-table>
      <template #footer>
        <el-button @click="logsDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getChannelStatus, testChannelConnection, getChannelLogs } from '@/api/channel'
import type { ChannelStatus, ChannelLog } from '@/api/channel'

// 响应式数据
const loading = ref(false)
const refreshLoading = ref(false)
const batchTestLoading = ref(false)
const channels = ref<ChannelStatus[]>([])
const testLoadingMap = ref<Record<string, boolean>>({})

// 搜索表单
const searchForm = reactive({
  channelName: '',
  channelType: '',
  connectionStatus: ''
})

// 状态统计
const statusCounts = reactive({
  connected: 0,
  disconnected: 0,
  warning: 0,
  error: 0
})

// 对话框
const detailDialog = reactive({
  visible: false,
  data: {} as ChannelStatus
})

const logsDialog = reactive({
  visible: false,
  logs: [] as ChannelLog[]
})

// 定时器
let refreshTimer: number | null = null

// 计算属性 - 过滤后的渠道列表
const filteredChannels = computed(() => {
  return channels.value.filter(channel => {
    const nameMatch = !searchForm.channelName || channel.channelName.toLowerCase().includes(searchForm.channelName.toLowerCase())
    const typeMatch = !searchForm.channelType || channel.channelType === searchForm.channelType
    const statusMatch = !searchForm.connectionStatus || channel.connectionStatus === searchForm.connectionStatus
    return nameMatch && typeMatch && statusMatch
  })
})

// 获取渠道状态数据
const fetchChannelStatus = async () => {
  loading.value = true
  try {
    const { data } = await getChannelStatus()
    channels.value = data
    updateStatusCounts()
  } catch (error) {
    ElMessage.error('获取渠道状态失败')
  } finally {
    loading.value = false
  }
}

// 更新状态统计
const updateStatusCounts = () => {
  statusCounts.connected = channels.value.filter(c => c.connectionStatus === 'connected').length
  statusCounts.disconnected = channels.value.filter(c => c.connectionStatus === 'disconnected').length
  statusCounts.warning = channels.value.filter(c => c.connectionStatus === 'warning').length
  statusCounts.error = channels.value.filter(c => c.connectionStatus === 'error').length
}

// 刷新状态
const refreshStatus = async () => {
  refreshLoading.value = true
  try {
    await fetchChannelStatus()
    ElMessage.success('状态刷新成功')
  } catch (error) {
    ElMessage.error('状态刷新失败')
  } finally {
    refreshLoading.value = false
  }
}

// 测试连接
const handleTestConnection = async (channel: ChannelStatus) => {
  testLoadingMap.value[channel.id] = true
  try {
    const result = await testChannelConnection(channel.id)
    if (result.success) {
      ElMessage.success('连接测试成功')
      // 更新本地状态
      const index = channels.value.findIndex(c => c.id === channel.id)
      if (index !== -1) {
        channels.value[index].connectionStatus = 'connected'
        channels.value[index].lastCheckTime = new Date().toISOString()
      }
    } else {
      ElMessage.error('连接测试失败: ' + result.message)
    }
  } catch (error) {
    ElMessage.error('连接测试失败')
  } finally {
    testLoadingMap.value[channel.id] = false
  }
}

// 批量测试
const handleBatchTest = async () => {
  batchTestLoading.value = true
  let successCount = 0
  let failCount = 0
  
  for (const channel of channels.value) {
    try {
      const result = await testChannelConnection(channel.id)
      if (result.success) {
        successCount++
      } else {
        failCount++
      }
    } catch (error) {
      failCount++
    }
  }
  
  batchTestLoading.value = false
  ElMessage.success(`批量测试完成，成功: ${successCount}，失败: ${failCount}`)
  await fetchChannelStatus() // 重新获取状态
}

// 查看详情
const handleViewDetails = (channel: ChannelStatus) => {
  detailDialog.data = channel
  detailDialog.visible = true
}

// 查看日志
const handleViewLogs = async (channel: ChannelStatus) => {
  try {
    const { data } = await getChannelLogs(channel.id)
    logsDialog.logs = data
    logsDialog.visible = true
  } catch (error) {
    ElMessage.error('获取日志失败')
  }
}

// 搜索和重置
const handleSearch = () => {
  // 搜索逻辑已在计算属性中实现
}

const handleReset = () => {
  searchForm.channelName = ''
  searchForm.channelType = ''
  searchForm.connectionStatus = ''
}

// 按状态筛选
const filterByStatus = (status: string) => {
  searchForm.connectionStatus = status
}

// 工具函数
const getChannelStatusClass = (channel: ChannelStatus) => {
  return `status-${channel.connectionStatus}`
}

const getChannelTypeTag = (type: string) => {
  const tagTypes: Record<string, string> = {
    upstream: 'info',
    downstream: 'success',
    bank: 'primary',
    consumer_finance: 'warning',
    small_loan: 'danger'
  }
  return tagTypes[type] || 'info'
}

const getChannelTypeLabel = (type: string) => {
  const labels: Record<string, string> = {
    upstream: '上游渠道',
    downstream: '下游渠道',
    bank: '银行',
    consumer_finance: '消费金融',
    small_loan: '小贷公司'
  }
  return labels[type] || type
}

const getConnectionStatusTag = (status: string) => {
  const tagTypes: Record<string, string> = {
    connected: 'success',
    disconnected: 'danger',
    warning: 'warning',
    error: 'danger'
  }
  return tagTypes[status] || 'info'
}

const getConnectionStatusText = (status: string) => {
  const texts: Record<string, string> = {
    connected: '正常连接',
    disconnected: '连接断开',
    warning: '状态警告',
    error: '状态异常'
  }
  return texts[status] || status
}

const getSuccessRateClass = (rate: number) => {
  if (rate >= 90) return 'text-success'
  if (rate >= 70) return 'text-warning'
  return 'text-danger'
}

const formatTime = (time: string) => {
  if (!time) return '-'
  return new Date(time).toLocaleString()
}

// 定时刷新
const startAutoRefresh = () => {
  refreshTimer = window.setInterval(() => {
    fetchChannelStatus()
  }, 30000) // 30秒刷新一次
}

const stopAutoRefresh = () => {
  if (refreshTimer) {
    window.clearInterval(refreshTimer)
    refreshTimer = null
  }
}

// 生命周期
onMounted(() => {
  fetchChannelStatus()
  startAutoRefresh()
})

onUnmounted(() => {
  stopAutoRefresh()
})
</script>

<style scoped>
.channel-monitor {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

/* 状态统计卡片 */
.status-statistics {
  margin-bottom: 30px;
}

.status-card {
  padding: 20px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 15px;
}

.status-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
}

.status-card.connected {
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
  border: 1px solid #b3d8ff;
}

.status-card.disconnected {
  background: linear-gradient(135deg, #fff1f0 0%, #ffebe6 100%);
  border: 1px solid #ffccc7;
}

.status-card.warning {
  background: linear-gradient(135deg, #fffbe6 0%, #fff8e6 100%);
  border: 1px solid #ffe58f;
}

.status-card.error {
  background: linear-gradient(135deg, #fafafa 0%, #f5f5f5 100%);
  border: 1px solid #d9d9d9;
}

.status-icon {
  padding: 12px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
}

.status-info {
  flex: 1;
}

.status-count {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.status-label {
  font-size: 14px;
  color: #606266;
}

/* 搜索表单 */
.search-form {
  margin-bottom: 20px;
}

/* 渠道状态列表 */
.channel-status-list {
  margin-top: 20px;
}

.channel-card {
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.channel-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
}

.channel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.channel-name {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.channel-status {
  margin-bottom: 15px;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

.status-indicator.connected .status-dot {
  background-color: #67c23a;
}

.status-indicator.disconnected .status-dot {
  background-color: #f56c6c;
}

.status-indicator.warning .status-dot {
  background-color: #e6a23c;
}

.status-indicator.error .status-dot {
  background-color: #909399;
}

@keyframes pulse {
  0% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.7;
    transform: scale(1.1);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

.status-text {
  font-size: 14px;
  font-weight: 500;
}

.last-check-time {
  font-size: 12px;
  color: #909399;
}

.channel-metrics {
  margin-bottom: 15px;
}

.metric-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.metric-label {
  font-size: 14px;
  color: #606266;
}

.metric-value {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.channel-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.error-info {
  margin-top: 15px;
}

.text-success {
  color: #67c23a;
}

.text-warning {
  color: #e6a23c;
}

.text-danger {
  color: #f56c6c;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .channel-monitor {
    padding: 10px;
  }
  
  .status-card {
    padding: 15px;
  }
  
  .status-count {
    font-size: 20px;
  }
  
  .channel-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .channel-actions {
    width: 100%;
    justify-content: flex-start;
  }
  
  .responsive-dialog {
    width: 95% !important;
  }
}

@media (max-width: 480px) {
  .status-card {
    flex-direction: column;
    text-align: center;
  }
  
  .status-icon {
    margin-bottom: 10px;
  }
}
</style>